import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { api } from '@/api'

export const useAuthStore = defineStore('auth', () => {
  // 状态
  const token = ref(localStorage.getItem('token') || '')
  const refreshToken = ref(localStorage.getItem('refreshToken') || '')
  const user = ref(null)
  const loading = ref(false)

  // 计算属性
  const isAuthenticated = computed(() => !!token.value && !!user.value)

  // 初始化用户信息
  const initAuth = async () => {
    if (token.value) {
      try {
        await getCurrentUser()
      } catch (error) {
        console.error('初始化认证失败:', error)
        logout()
      }
    }
  }

  // 登录
  const login = async (credentials) => {
    loading.value = true
    try {
      const response = await api.post('/auth/login', credentials)
      
      if (response.data.success) {
        const { user: userData, tokens } = response.data.data
        
        // 保存tokens
        token.value = tokens.accessToken
        refreshToken.value = tokens.refreshToken
        localStorage.setItem('token', tokens.accessToken)
        localStorage.setItem('refreshToken', tokens.refreshToken)
        
        // 保存用户信息
        user.value = userData
        
        return { success: true, user: userData }
      }
      
      return { success: false, message: response.data.message }
    } catch (error) {
      console.error('登录失败:', error)
      return {
        success: false,
        message: error.response?.data?.message || '登录失败'
      }
    } finally {
      loading.value = false
    }
  }

  // 注册
  const register = async (userData) => {
    loading.value = true
    try {
      const response = await api.post('/auth/register', userData)
      
      if (response.data.success) {
        const { user: newUser, tokens } = response.data.data
        
        // 自动登录
        token.value = tokens.accessToken
        refreshToken.value = tokens.refreshToken
        localStorage.setItem('token', tokens.accessToken)
        localStorage.setItem('refreshToken', tokens.refreshToken)
        
        user.value = newUser
        
        return { success: true, user: newUser }
      }
      
      return { success: false, message: response.data.message }
    } catch (error) {
      console.error('注册失败:', error)
      return {
        success: false,
        message: error.response?.data?.message || '注册失败'
      }
    } finally {
      loading.value = false
    }
  }

  // 登出
  const logout = async () => {
    try {
      if (refreshToken.value) {
        await api.post('/auth/logout', {
          refreshToken: refreshToken.value
        })
      }
    } catch (error) {
      console.error('登出请求失败:', error)
    } finally {
      // 清除本地数据
      token.value = ''
      refreshToken.value = ''
      user.value = null
      localStorage.removeItem('token')
      localStorage.removeItem('refreshToken')
    }
  }

  // 获取当前用户信息
  const getCurrentUser = async () => {
    try {
      const response = await api.get('/auth/me')
      
      if (response.data.success) {
        user.value = response.data.data.user
        return user.value
      }
      
      throw new Error('获取用户信息失败')
    } catch (error) {
      console.error('获取用户信息失败:', error)
      throw error
    }
  }

  // 刷新token
  const refreshAccessToken = async () => {
    if (!refreshToken.value) {
      throw new Error('没有刷新令牌')
    }

    try {
      const response = await api.post('/auth/refresh', {
        refreshToken: refreshToken.value
      })

      if (response.data.success) {
        const { tokens } = response.data.data
        
        token.value = tokens.accessToken
        refreshToken.value = tokens.refreshToken
        localStorage.setItem('token', tokens.accessToken)
        localStorage.setItem('refreshToken', tokens.refreshToken)
        
        return tokens.accessToken
      }
      
      throw new Error('刷新令牌失败')
    } catch (error) {
      console.error('刷新令牌失败:', error)
      logout()
      throw error
    }
  }

  // 修改密码
  const changePassword = async (passwordData) => {
    loading.value = true
    try {
      const response = await api.put('/auth/change-password', passwordData)
      
      if (response.data.success) {
        // 修改密码后需要重新登录
        logout()
        return { success: true, message: response.data.message }
      }
      
      return { success: false, message: response.data.message }
    } catch (error) {
      console.error('修改密码失败:', error)
      return {
        success: false,
        message: error.response?.data?.message || '修改密码失败'
      }
    } finally {
      loading.value = false
    }
  }

  // 更新用户信息
  const updateProfile = async (profileData) => {
    loading.value = true
    try {
      const response = await api.put(`/users/${user.value._id}`, profileData)
      
      if (response.data.success) {
        user.value = { ...user.value, ...response.data.data.user }
        return { success: true, user: user.value }
      }
      
      return { success: false, message: response.data.message }
    } catch (error) {
      console.error('更新用户信息失败:', error)
      return {
        success: false,
        message: error.response?.data?.message || '更新用户信息失败'
      }
    } finally {
      loading.value = false
    }
  }

  return {
    // 状态
    token,
    refreshToken,
    user,
    loading,
    
    // 计算属性
    isAuthenticated,
    
    // 方法
    initAuth,
    login,
    register,
    logout,
    getCurrentUser,
    refreshAccessToken,
    changePassword,
    updateProfile
  }
})